<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
      <el-form-item label="所属项目" prop="projectId">
        <el-select
            class="search-width"
            filterable clearable v-model="queryParams.projectId" placeholder="请选择所属项目">
          <el-option
              v-for="item in allProjectList"
              :key="item.id"
              :label="item.projectName"
              :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="甲方名称" prop="principalName">
        <el-input maxlength="50"
                  class="search-width"
                  v-model="queryParams.principalName"
                  placeholder="请输入委托方名称"
                  clearable
                  @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="受托方名称" prop="trusteeName">
        <el-input maxlength="50"
                  class="search-width"
                  v-model="queryParams.trusteeName"
                  placeholder="请输入受托方名称"
                  clearable
                  @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="项目类型" prop="classifyCode">
        <el-select filterable clearable
                   class="search-width"
                   v-model="queryParams.classifyCode" placeholder="请选择项目类型">
          <el-option
              v-for="dict in project_classify"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="费用类型" prop="costType">
        <el-select class="search-width" v-model="queryParams.costType" placeholder="请选择费用类型" clearable>
          <el-option
              v-for="item in costTypeList"
              :key="item.code"
              :label="item.name"
              :value="item.code"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['biz:bizCost:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['biz:bizCost:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['biz:bizCost:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['biz:bizCost:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="bizCostList" border>
      <el-table-column type="expand">
        <template #default="props">
          <el-table :data="props.row.costList"
                    row-class-name="success-row"
                    border
                    style="width:calc(100vw - 90px)"
                    @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="left"/>
            <el-table-column label="序号" type="index" align="left" width="60"/>
            <el-table-column label="费用类型" align="left" prop="costType" width="180">
              <template #default="scope">
                <span>{{ getTypeName(scope.row.costType) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="金额" align="left" prop="costMoney" width="180">
              <template #default="scope">
                <span>{{ formatMoney(scope.row.costMoney) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="复核人" align="left" prop="reviewUserName" width="120"/>
            <el-table-column label="备注" align="left" prop="memo" show-overflow-tooltip/>
            <el-table-column label="创建人" align="left" prop="userName" width="120"/>
            <el-table-column label="创建时间" align="left" prop="createTime" width="180"/>
            <el-table-column label="操作" align="left" width="120" class-name="small-padding fixed-width">
              <template #default="scope">
                <el-tooltip content="复核" placement="top">
                  <el-button v-if="Number(scope.row.costType)<=2" link type="primary" icon="Stopwatch"
                             @click="handleReview(scope.row)"
                             v-hasPermi="['biz:bizInvoice:review']">
                  </el-button>
                </el-tooltip>
                <el-tooltip content="修改" placement="top">
                  <el-button link type="primary" icon="Edit"
                             @click="handleUpdate(scope.row)"
                             v-hasPermi="['biz:bizInvoice:edit']">
                  </el-button>
                </el-tooltip>
                <el-tooltip content="删除" placement="top">
                  <el-button v-if="Number(scope.row.costType)>=6" link type="primary" icon="Delete"
                             @click="handleDelete(scope.row)"
                             v-hasPermi="['biz:bizInvoice:remove']">
                  </el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-table-column>
      <el-table-column label="序号" type="index" align="left" width="60"/>
      <el-table-column label="项目名称" align="left" prop="projectName" min-width="200" show-overflow-tooltip/>
      <el-table-column label="合同金额" align="left" prop="totalAmount" width="120">
        <template #default="scope">
          <span>{{ formatMoney(scope.row.totalAmount) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="渠道费" align="left" prop="channelCost" width="120">
        <template #default="scope">
          <span>{{ formatMoney(scope.row.channelCost) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="渠道税费" align="left" prop="channelTax" width="120">
        <template #default="scope">
          <span>{{ formatMoney(scope.row.channelTax) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="项目实得合同额" align="left" prop="realIncome" width="120">
        <template #default="scope">
          <span>{{ formatMoney(scope.row.realIncome) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="成本支出" align="left" prop="costAmount" width="120">
        <template #default="scope">
          <span>{{ formatMoney(scope.row.costAmount) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="暂估税后利润" align="left" prop="profit" width="120">
        <template #default="scope">
          <span>{{ formatMoney(scope.row.profit) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="暂估技术绩效" align="left" prop="performance" width="120">
        <template #default="scope">
          <span>{{ formatMoney(scope.row.agreePerformance) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="暂估管理绩效" align="left" prop="marketPerformance" width="120">
        <template #default="scope">
          <span>{{ formatMoney(scope.row.managePerformance) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="暂估市场绩效" align="left" prop="marketPerformance" width="120">
        <template #default="scope">
          <span>{{ formatMoney(scope.row.marketPerformance) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="暂估最终利润" align="left" prop="finalProfit" width="120">
        <template #default="scope">
          <span>{{ formatMoney(scope.row.finalProfit) }}</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" align="left" width="110">
        <template #default="scope">
          <el-button link type="primary" icon="Document" @click="handleNew(scope.row)"
                     v-hasPermi="['biz:bizInvoice:edit']">成本登记
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改成本开支对话框 -->
    <el-dialog :close-on-click-modal="false" draggable :title="title" v-model="open" width="800px" append-to-body
               @close="cancel">
      <el-form ref="bizCostRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="所属项目" prop="projectId">
          <el-select :disabled="!selectProject" filterable v-model="form.projectId" placeholder="请选择所属项目">
            <el-option
                v-for="item in allProjectList"
                :key="item.id"
                :label="item.projectName"
                :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="费用类型" prop="costType">
          <el-select :disabled="!selectType" v-model="form.costType" placeholder="请选择费用类型">
            <el-option
                v-for="item in costTypeList"
                :key="item.code"
                :label="item.name"
                :value="item.code"
                :disabled="item.disabled"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="金额" prop="costMoney">
          <CurrencyInput maxlength="50" v-model="form.costMoney" placeholder="请输入金额"/>
        </el-form-item>
        <el-form-item label="备注" prop="memo">
          <el-input maxlength="500" :disabled="review" v-model="form.memo" type="textarea"
                    :placeholder="!review?'请输入内容':''"/>
        </el-form-item>
        <!--        <el-form-item label="比例" prop="proportion" v-if="review">-->
        <!--          <PercentInput v-model="form.proportion" placeholder="请输入比例"/>-->
        <!--        </el-form-item>-->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="BizCost">
import {listBizCost, getBizCost, delBizCost, addBizCost, updateBizCost, listCostType} from "@/api/biz/bizCost";
import {listAllProject} from "@/api/biz/bizProject";
import CurrencyInput from '@/components/CurrencyInput.vue';
import PercentInput from '@/components/PercentInput.vue';
import {currentDate} from '@/utils/dateutil';
import {formatMoney} from '@/utils/money';

const {proxy} = getCurrentInstance();
const route = useRoute();
const router = useRouter();
const paramProjectId = ref('');
paramProjectId.value = route.query.receiptProjectId;
// 计算属性用于获取查询参数 t
const queryParamT = computed(() => route.query.receiptProjectId);
// 监听 queryParamT 的变化
watch(queryParamT, (newValue, oldValue) => {
  paramProjectId.value = newValue;
  costListAllProject();
});
const {
  project_classify
} = proxy.useDict('project_classify');

const costTypeList = ref([]);
const allProjectList = ref([]);
const bizCostList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const review = ref(false);
const selectProject = ref(true);
const selectType = ref(true);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    projectId: null,
    projectName: null,
    principalName: null,
    trusteeName: null,
    classifyCode: null,
    costType: null,
  },
  rules: {
    projectId: [
      {required: true, message: "所属项目不能为空", trigger: "submit"}
    ],
    costType: [
      {required: true, message: "费用类型不能为空", trigger: "submit"}
    ],
    costMoney: [
      {required: true, message: "金额不能为空", trigger: "submit"}
    ],
  }
});

const {queryParams, form, rules} = toRefs(data);

/** 查询成本开支列表 */
function getList() {
  loading.value = true;
  listBizCost(queryParams.value).then(response => {
    bizCostList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    createTime: null,
    updateTime: null,
    deleted: null,
    projectId: null,
    costType: null,
    costMoney: null,
    memo: null,
    reviewUserId: null,
    proportion: 0,
    status: null,
    userId: null
  };
  proxy.resetForm("bizCostRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  selectProject.value = true;
  selectType.value = true;
  open.value = true;
  title.value = "添加成本开支";
}

function handleNew(row) {
  reset();
  selectProject.value = false;
  selectType.value = true;
  open.value = true;
  review.value = false;
  title.value = "添加成本开支";
  form.value.projectId = row.projectId;
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getBizCost(_id).then(response => {
    form.value = response.data;
    selectProject.value = false;
    selectType.value = false;
    open.value = true;
    review.value = false;
    title.value = "修改成本开支";
  });
}

function handleReview(row) {
  reset();
  const _id = row.id || ids.value
  getBizCost(_id).then(response => {
    form.value = response.data;
    selectProject.value = false;
    selectType.value = false;
    open.value = true;
    review.value = true;
    title.value = "复核";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["bizCostRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateBizCost(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addBizCost(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除成本开支数据项？').then(function () {
    return delBizCost(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('biz/bizCost/export', {
    ...queryParams.value
  }, `成本开支-${currentDate()}.xlsx`)
}

function costListAllProject() {
  listAllProject({}).then(response => {
    allProjectList.value = response.data;
    if (paramProjectId.value) {
      //参数存在，打开弹窗
      reset();
      open.value = true;
      title.value = "添加成本开支";
      form.value.projectId = Number(paramProjectId.value);
    }
  });
}

function getListCostType() {
  listCostType({}).then(response => {
    costTypeList.value = response.data;
  });
}

const getTypeName = (code) => {
  const item = costTypeList.value.find(item => item.code == code);
  return item ? item.name : '-';
}

function updateAfter(data) {
  for (var i = 0; i < bizCostList.value.length; i++) {
    const itemToUpdate = bizCostList.value[i].costList.find(item => item.id === data.id);
    if (itemToUpdate) {
      console.log('find!!!!', itemToUpdate)
      itemToUpdate.costMoney = data.costMoney;
      itemToUpdate.memo = data.memo;
      break;
    }
  }
  // bizCostList.value = bizCostList.value.map(item => {
  //   const updatedCostList = item.costList.map(cost => {
  //     if (cost.id === data.id) {
  //       return { ...cost, costMoney: data.costMoney,memo:data.memo };
  //     }
  //     return cost;
  //   });
  //
  //   return { ...item, costList: updatedCostList };
  // });
}

getListCostType();
getList();
costListAllProject();
</script>
<style>
.el-table .success-row {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}
</style>
